package org.kl.bf.service.basic;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.Attachment;
import org.kl.bf.entity.basic.AttachmentMaster;
import org.kl.bf.repository.basic.AttachmentDao;
import org.kl.bf.repository.basic.AttachmentMasterDao;
import org.kl.bf.web.base.BasicController;
import org.kl.auditsupervision.utils.AuditsupervisionConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Collections3;

import com.alibaba.fastjson.JSON;

import freemarker.template.Template;

/**
 * 
 * @author Qken
 * @date 2014年3月28日
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class AttachmentService {
	@Autowired
	private AttachmentDao attachmentDao;
	@Autowired
	private AttachmentMasterDao attachmentMasterDao;

	public Attachment getAttachment(String guid) {
		return attachmentDao.findOne(guid);
	}

	public void saveAttachment(Attachment entity) {
		attachmentDao.save(entity);
	}

	public void deleteAttachment(String guid) {
		attachmentDao.delete(guid);
	}

	public Page<Attachment> getAttachment(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType, String orderType) {
		return attachmentDao.getPage(searchParams, pageNumber, pageSize, sortType, orderType, Attachment.class);
	}
	
	/**
	 * 删除附件
	 */
	public boolean deleteAttachment(String id, String action) {
		Attachment attachment = attachmentDao.findOne(id);
		// 删除时，同时将文件放入回收站
		try {
			File file = new File(attachment.getFilePath());
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String uploadPath = AuditsupervisionConstants.UPLOAD_PATH;
			String recyclePath = AuditsupervisionConstants.RECYCLE_PATH;
			File destFile = new File(attachment.getFilePath().replace(
					uploadPath, recyclePath)
					+ "_" + df.format(new Date()) + action);
			FileUtils.moveFile(file, destFile);
			attachmentDao.delete(id);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	
	public void save(Attachment attachment) {
		attachmentDao.save(attachment);
	}

	/**
	 * 行编辑保存附件信息
	 * @param attachUpdated
	 */
	public void save(String attachUpdated) {
		if (StringUtils.isNoneBlank(attachUpdated)) {
			List<Attachment> updates = JSON.parseArray(attachUpdated, Attachment.class);
			if (Collections3.isNotEmpty(updates)) {
				for (Attachment a : updates) {
					attachmentDao.save(a);
				}
			}
		}
	}
	
	
	public List<Attachment> findByAttachmentMasterIdAndAttachmentType(String id,String attachmentType){
		 return attachmentDao.findByAttachmentMasterIdAndAttachmentType(id, attachmentType);
	}

	/**
	 * 保存文本到指定路径<物资采购合同>
	 */
	public void save(String id, String fileName, Map<String, Object> dataMap, Template temp) {
		AttachmentMaster attachMaster = attachmentMasterDao.findOne(id);
		String path = AuditsupervisionConstants.UPLOAD_PATH;
		path += File.separator + attachMaster.getLevelType1() + File.separator + attachMaster.getLevelType2()
				+ File.separator;
		// 创建文件夹
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		File outFile = new File(path + fileName);
		OutputStream oStream = null;
		Writer out = null;
		try {
			// 写数据库信息
			// 1.将原来的附件放入回收站
			List<Attachment> oldList = attachmentDao.findByAttachmentMasterIdAndFileType(attachMaster.getId(), "合同文本");
			if (oldList.size() > 0) {
				for (Attachment old : oldList) {
					deleteAttachment(old.getId(), "覆盖");
				}
			}
			oStream = new BufferedOutputStream(new FileOutputStream(outFile));
			out = new BufferedWriter(new OutputStreamWriter(oStream, "utf-8"));
			temp.process(dataMap, out);
			// 2.插入新附件
			Attachment attachment = new Attachment();
			attachment.setFileName(fileName);
			attachment.setFilePath(path + fileName);
			attachment.setFileSize(outFile.length() + "");
			attachment.setUploadTime(new Date());
			attachment.setUploadUserId(BasicController.getCurrentUserId());
			attachment.setFileType("合同文本");
			attachment.setAttachmentMasterId(attachMaster.getId());
			attachmentDao.save(attachment);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
